﻿/*
Copyright 2010 Andy Uhl

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.IsolatedStorage;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text.RegularExpressions;
using ManagedWinapi;
using System.Resources;
using System.Reflection;
using ListMaker.App.Properties;

namespace ListMaker.App
{
	public partial class MainForm : Form
	{
		private const string KEYBOARD_SHORTCUT_FILE = "KeyboardShortcut";
		private IDictionary<string, Preset> presets;
		private static Regex newlineRegex = new Regex(@"[\r\n]+", RegexOptions.Compiled | RegexOptions.Multiline);
		private static Regex commaRegex = new Regex(@",+", RegexOptions.Compiled | RegexOptions.Multiline);
		private static Regex tabRegex = new Regex(@"\t+", RegexOptions.Compiled | RegexOptions.Multiline);
		private static Regex wsRegex = new Regex(@"\s+", RegexOptions.Compiled | RegexOptions.Multiline);
		private Hotkey hotkey;
		private OptionsForm optionsForm;
		private bool hotkeyWarned = false;

		public MainForm()
		{
			InitializeComponent();
		}

		#region "MainForm Events"
		private void MainForm_Load(object sender, EventArgs e)
		{
			inputSplit.Items.AddRange(Enum.GetNames(typeof(InputSplitOptions)));
			inputSplit.SelectedIndex = inputSplit.FindStringExact(Enum.GetName(typeof(InputSplitOptions), InputSplitOptions.NewLine));

			Keys keys = Settings.Default.KeyboardShortcut;
			KeyboardShortcut = new KeyEventArgs(keys);
			//SetHotkeysEnabled(true);

			inputSplit.SelectedIndex = inputSplit.FindString("Newline");
			LoadPresets();
			
			input.Text = GetClipboardText();
		}

		private void MainForm_Activated(object sender, EventArgs e)
		{
			SetHotkeysEnabled(false);
			Preview();
		}

		private void MainForm_Deactivate(object sender, EventArgs e)
		{
			SetHotkeysEnabled(true);
		}

		private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (e != null && e.CloseReason == CloseReason.UserClosing)
			{
				e.Cancel = true;
				Hide();
				return;
			}

			trayIcon.Visible = false;
			trayIcon.Dispose();
			trayIcon = null;

			SetHotkeysEnabled(false);
		}

		private void ok_Click(object sender, EventArgs e)
		{
			string newText = GetProcessedText();
			Clipboard.Clear();
			Clipboard.SetText(newText);
			Hide();
		}

		private void cancel_Click(object sender, EventArgs e)
		{
			Hide();
		}
		#endregion

		private void Preview()
		{
			input.Text = GetClipboardText();
			preview.Text = GetProcessedText();
		}

		private string GetProcessedText()
		{
			List<string> items;
			switch (inputSplit.Text)
			{
				case "Whitespace":
					items = wsRegex.Split(GetClipboardText()).ToList();
					break;
				case "Tab":
					items = tabRegex.Split(GetClipboardText()).ToList();
					break;
				case "Comma":
					items = commaRegex.Split(GetClipboardText()).ToList();
					break;
				case "Newline":
				default:
					items = newlineRegex.Split(GetClipboardText()).ToList();
					break;
			}

			List<string> processed = new List<string>();

			foreach (string item in items)
			{
				string temp = item;

				if (trimWhitespace.Checked)
					temp = temp.Trim();

				if (removeNull.Checked && temp.ToUpperInvariant() == "NULL")
					continue;

				temp = outputPrefix.Text + temp + outputPostfix.Text;

				processed.Add(temp);
			}

			if (singleLine.Checked)
			{
				return string.Join(outputSeparator.Text, processed);
			}
			else
			{
				return string.Join(outputSeparator.Text + Environment.NewLine, processed);
			}
		}

		private static string GetClipboardText()
		{
			IDataObject dataObj = Clipboard.GetDataObject();

			if (!dataObj.GetDataPresent(DataFormats.Text))
			{
				return string.Empty;
			}
			else
			{
				return dataObj.GetData(DataFormats.Text).ToString();
			}
		}

		#region Tray Icon
		private void trayIcon_MouseDoubleClick(object sender, MouseEventArgs e)
		{
			if (e.Button == System.Windows.Forms.MouseButtons.Left)
			{
				WindowState = FormWindowState.Normal;
				Show();
				Activate();
			}
		}

		private void exitMenuItem_Click(object sender, EventArgs e)
		{
			Application.Exit();
		}

		private void optionsMenuItem_Click(object sender, EventArgs e)
		{
			if (optionsForm == null)
			{
				optionsForm = new OptionsForm();
				optionsForm.Owner = this;
				optionsForm.FormClosed += new FormClosedEventHandler(optionsForm_FormClosed);
			}

			optionsForm.Show();
			optionsForm.Activate();
		}

		void optionsForm_FormClosed(object sender, FormClosedEventArgs e)
		{
			optionsForm = null;
		}
		#endregion

		#region Keyboard Shortcuts
		internal void SetHotkeysEnabled(bool enabled)
		{
			if (hotkey != null)
			{
				try
				{
					hotkey.Enabled = enabled;
				}
				catch (HotkeyAlreadyInUseException)
				{
					hotkey.Enabled = false;

					if (!hotkeyWarned)
					{
						hotkeyWarned = true;
						MessageBox.Show(
							"Disabling hotkey " + OptionsForm.GetKeysText(KeyboardShortcut) + " because it is already in use by another application.",
							"List Maker",
							MessageBoxButtons.OK,
							MessageBoxIcon.Warning
						);
					}
				}
			}
		}

		void hotkey_HotkeyPressed(object sender, EventArgs e)
		{
			//hotkey.Enabled = false;
			Show();
			Activate();
		}

		internal static bool IsKeyboardShortcutAvailable(KeyEventArgs keys)
		{
			using (Hotkey test = new Hotkey())
			{
				test.Ctrl = keys.Control;
				test.Shift = keys.Shift;
				test.KeyCode = keys.KeyCode;
				test.Alt = keys.Alt;
				test.WindowsKey = (keys.KeyCode == Keys.LWin || keys.KeyCode == Keys.LWin);

				try
				{
					test.Enabled = true;
					test.Enabled = false;
					return true;
				}
				catch (HotkeyAlreadyInUseException)
				{
					return false;
				}
			}
		}

		public KeyEventArgs KeyboardShortcut
		{
			get
			{
				return _keyboardShortcut;
			}
			internal set
			{
				_keyboardShortcut = value;

				if (_keyboardShortcut != null)
				{
					if (hotkey != null)
					{
						hotkey.Dispose();
						hotkey = null;
					}

					hotkey = new Hotkey();
					hotkey.Ctrl = _keyboardShortcut.Control;
					hotkey.Shift = _keyboardShortcut.Shift;
					hotkey.KeyCode = _keyboardShortcut.KeyCode;
					hotkey.Alt = _keyboardShortcut.Alt;
					hotkey.WindowsKey = (_keyboardShortcut.KeyCode == Keys.LWin || _keyboardShortcut.KeyCode == Keys.LWin);
					hotkey.HotkeyPressed += new EventHandler(hotkey_HotkeyPressed);

					//SaveToIsolatedStorage(_keyboardShortcut.KeyData, "KeyboardShortcut");
					Settings.Default.KeyboardShortcut = _keyboardShortcut.KeyData;
				}
			}
		}
		private KeyEventArgs _keyboardShortcut;
		#endregion

		#region Refresh Screen Events
		private void presetsListView_Click(object sender, EventArgs e)
		{
			if (presetsListView.SelectedItems.Count == 1)
			{
				Preset preset = presets[presetsListView.SelectedItems[0].Name];

				outputPrefix.Text = preset.Prefix;
				outputPostfix.Text = preset.Postfix;
				outputSeparator.Text = preset.Separator;
				removeNull.Checked = preset.RemoveNull;
				singleLine.Checked = preset.SingleLine;
				trimWhitespace.Checked = preset.TrimWhiteSpace;
				inputSplit.SelectedIndex = inputSplit.FindStringExact(Enum.GetName(typeof(InputSplitOptions), preset.InputSplitOption));
			}

			Preview();
		}

		private void prefix_TextChanged(object sender, EventArgs e)
		{
			Preview();
		}

		private void postfix_TextChanged(object sender, EventArgs e)
		{
			Preview();
		}

		private void separator_TextChanged(object sender, EventArgs e)
		{
			Preview();
		}

		private void trimWhitespace_CheckedChanged(object sender, EventArgs e)
		{
			Preview();
		}

		private void removeNull_CheckedChanged(object sender, EventArgs e)
		{
			Preview();
		}

		private void singleLine_CheckedChanged(object sender, EventArgs e)
		{
			Preview();
		}

		private void inputSplit_SelectedIndexChanged(object sender, EventArgs e)
		{
			Preview();
		}

		#endregion

		private void aboutMenuItem_Click(object sender, EventArgs e)
		{
			using (About about = new About())
			{
				about.ShowDialog();
			}
		}

		#region Presets
		private void LoadPresets()
		{
			presets = PresetHelper.LoadPresets();

			RefreshPresets();
		}

		private void RefreshPresets()
		{
			presetsListView.Items.Clear();
			foreach (KeyValuePair<string, Preset> pair in presets)
			{
				Preset preset = pair.Value;
				ListViewItem item = new ListViewItem();
				item.Name = preset.Name;
				item.Text = preset.Name;

				presetsListView.Items.Add(item);
			}
		}

		private void presetsListView_SelectedIndexChanged(object sender, EventArgs e)
		{
			deleteMenuItem.Enabled = presetsListView.SelectedItems.Count > 0;
			renameMenuItem.Enabled = presetsListView.SelectedItems.Count > 0;
		}

		private void saveSettingsAsPresetMenuItem_Click(object sender, EventArgs e)
		{
			using (PresetNameForm form = new PresetNameForm())
			{
				if (form.ShowDialog() == DialogResult.OK)
				{
					Preset preset = new Preset();
					preset.Name = form.PresetName;

					preset.Prefix = outputPrefix.Text;
					preset.Postfix = outputPostfix.Text;
					preset.Separator = outputSeparator.Text;
					preset.RemoveNull = removeNull.Checked;
					preset.SingleLine = singleLine.Checked;
					preset.TrimWhiteSpace = trimWhitespace.Checked;
					preset.InputSplitOption = (InputSplitOptions)Enum.Parse(typeof(InputSplitOptions), inputSplit.SelectedItem.ToString());

					PresetHelper.SavePreset(preset);
					presets.Add(preset.Name, preset);

					RefreshPresets();
				}
			}
		}

		private void deleteMenuItem_Click(object sender, EventArgs e)
		{
			if (presetsListView.SelectedItems.Count > 0)
			{
				if (MessageBox.Show("Are you sure you want to delete this preset?", "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
				{
					Preset preset = presets[presetsListView.SelectedItems[0].Name];
					presets.Remove(presetsListView.SelectedItems[0].Name);
					PresetHelper.DeletePreset(preset);
					
					RefreshPresets();
				}
			}
		}
		
		private void renameMenuItem_Click(object sender, EventArgs e)
		{
			if (presetsListView.SelectedItems.Count > 0)
			{
				using (PresetNameForm form = new PresetNameForm())
				{
					form.PresetName = presetsListView.SelectedItems[0].Name;

					if (form.ShowDialog() == DialogResult.OK)
					{
						Preset preset = presets[presetsListView.SelectedItems[0].Name];
						presets.Remove(presetsListView.SelectedItems[0].Name);
						PresetHelper.RenamePreset(preset, form.PresetName);
						presets.Add(preset.Name, preset);

						RefreshPresets();
					}
				}
			}
		}
		#endregion
	}
}
